<template>
  <div style="padding: 10px">
    <el-card>
      <div style="display: flex;">
        <div style="width: 300px">
          <el-image :src="goods.pic" :preview-src-list="[goods.pic]" style="width: 100%"></el-image>
        </div>
        <div style="flex: 1; padding-left: 50px">
          <div class="item1"><h3>{{ goods.name }}</h3></div>
          <div class="item1" style="font-size: 14px; ">{{ goods.subtitle }}</div>
          <div class="item1" style="color: #005488" v-if="goods.promotionPrice">促销价格 ￥ {{ goods.promotionPrice }}</div>
          <div class="item1" style="color: #005488" v-if="goods.promotionStartTime">促销开始时间 {{
              goods.promotionStartTime
            }}
          </div>
          <div class="item1" style="color: #005488" v-if="goods.promotionEndTime">促销结束时间 {{
              goods.promotionEndTime
            }}
          </div>

          <el-card class="item1" style="color: #005488" v-if="goods.frontCateAttributeDto">分类
            <div v-for="cateDto in goods.frontCateAttributeDto">
              {{ cateDto.name }}：
              <el-checkbox-group v-model="selectA"
                                 :min="0"
                                 :max="2">
                <el-checkbox v-for="item in getInputListArr(cateDto.inputList)" :label="item" :key="item"
                             class="littleMarginLeft"></el-checkbox>
              </el-checkbox-group>
            </div>
          </el-card>
<!--          <el-card class="item1" style="color: #005488" v-if="goods.stockList">分类-->
<!--            <div v-for="cateDto in goods.stockList">-->
<!--              <el-checkbox-group v-model="selectA"-->
<!--                                 :min="0"-->
<!--                                 :max="2">-->
<!--                <el-checkbox v-for="item in cateDto.spData" :label="item" :key="item.name"-->
<!--                             class="littleMarginLeft"></el-checkbox>-->
<!--              </el-checkbox-group>-->
<!--            </div>-->
<!--          </el-card>-->
          <el-card>
            <div class="item1" style="color: #005488">您的选择 {{ selectA }}</div>
              <div class="item1" style="color: #005488">库存 {{ stock }}</div>
              <div class="item1" style="color: #005488">价格 ￥ {{ price }}</div>
          </el-card>
          <div class="item1" style="font-size: 14px; "><span style="margin-left: 10px">{{ goods.unit }}</span></div>
          <div class="item1">
            <el-input-number v-model="form.num" :min="1" :max="100" label="数量"></el-input-number>
            <span style="margin-left: 10px">{{ goods.unit }}</span>
          </div>
          <div class="item1" style ="margin-top: 40px" >
            <el-button size="medium" style="background-color: #ff6c37; color: white"><i class="el-icon-wallet" v-on:click="handleBuy"></i> 直接购买
            </el-button>
            <el-button size="medium" style="background-color: #005488; color: white" v-on:click="addCart(goods)" ><i
                class="el-icon-shopping-cart-2"></i> 加入购物车
            </el-button>
            <el-button size="medium" style="background-color: white; color: black; margin-right: 20px" @click="back"><i
                class="el-icon-back"></i> 返回
            </el-button>
          </div>

        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 15px">

      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="商品详情" name="detail">
          <div style="margin-top: 20px">
            <div style="flex:auto 0">
              <div style="flex:auto 0">
                <div class="item1" style="font-size: 16px;flex:auto 0">商品详情</div>
                <div v-html="goods.detailHtml" style="flex:auto 0"></div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商品评价" name="comment">
          <div style="margin-top: 20px">
            <div style="display: flex;">
              <div style="flex: 1;">
                <div class="item1" style="font-size: 16px; ">商品评价</div>
                <div class="item1" style="font-size: 16px; ">共有{{goods.commentCount}}条评价</div>
                <div v-if="goods.commentCount>0">
                  <el-card v-for="comment in goods.frontCommentDtoList" style="width: 100%">
                    <div class="item1" style="font-size: 14px; "><Strong>{{ comment.memberNickname }}</Strong></div>
                    <div class="item1" style="font-size: 14px; ">{{ comment.content }}</div>
                    <div class="item1" style="font-size: 14px; ">{{ comment.createTime }} <el-rate
                        v-model="comment.star"
                        disabled
                        show-score
                        text-color="#ff9900">
                    </el-rate></div>
                  </el-card>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

    </el-card>
    <el-dialog title="填写订单" :visible.sync="dialogFormVisible" width="80%">
      <el-form label-width="150px" size="small">
        <el-form-item label="收件人">
          <el-input
              :rows="1"
              placeholder="请输入收件人姓名"
              v-model="receiverName">
          </el-input>
        </el-form-item>

        <el-form-item label="联系方式">
          <el-input
              :rows="1"
              placeholder="请输入收件人电话"
              v-model="receiverPhone">
          </el-input>
        </el-form-item>

        <el-form-item label="收货地址" :inline="true">
          <v-distpicker :province="province"
                        :city="city"
                        :area="region"
                        @selected="onSelectRegion"></v-distpicker>

          <el-input v-model="receiverAddress" autocomplete="off" placeholder="请输入详细地址" style="width: 300px;margin-top: 10px">

          </el-input>
          <el-button @click="fill" type="primary" plain style="margin-left: 20px">表单填充</el-button>
        </el-form-item>




        <el-form-item label="商品信息">
          <el-table :data="productList">
            <el-table-column prop="pic" label="商品图片" width="125" align="center">
              <template v-slot="scope">
                <el-image :src="scope.row.pic" ></el-image>
              </template>
            </el-table-column>
            <el-table-column  prop="name" label="商品名称" align="center" width="250">
            </el-table-column>
            <el-table-column prop="price" label="商品原价" align="center">
            </el-table-column>
            <el-table-column  label="数量" align="center" width="160">
              <div>{{this.form.num}}</div>
            </el-table-column>
            <el-table-column label="总金额" align="center" >
                <div style="color: orangered">{{this.goods.price * this.form.num}}</div>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="订单总金额">
          <div>{{this.goods.price * this.form.num }}</div>
        </el-form-item>

        <el-form-item label="优惠券">
          <el-table :data="this.couponList"  highlight-current-row ref="singleTable" @selection-change="handleSelectionChange1">
            <el-table-column type="selection" width="55" :selectable="checkSelectable"></el-table-column>
            <el-table-column prop="name" label="优惠券名称" width="125" align="center">
            </el-table-column>
            <el-table-column prop="minPoint" label="使用门槛" align="center" width="250">
            </el-table-column>
            <el-table-column prop="amount" label="金额" align="center" width="160">
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="优惠金额">
          <div>{{this.couponAmount}}</div>
        </el-form-item>

        <el-form-item label="应付金额">
          <div>{{this.form.num*this.goods.price - this.couponAmount}}</div>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="textarea">
          </el-input>
        </el-form-item>
      </el-form>
      <div style="margin-top: 20px;text-align: center">
        <el-button type="primary" @click="handleSubmit">提交订单</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VDistpicker from 'v-distpicker';
export default {
  name: "Detail",
  components: {
    VDistpicker
  },
  data() {
    return {
      // id: this.$route.query.id,
      selectA: [],
      price: [],
      receiverName:'',
      receiverPhone:'',
      stock:[],
      goods: {},
      cartItem:{},
      form: {num: 1},
      receiverAddress:'',
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      memberId:localStorage.getItem("id"),
      activeTab: 'detail',
      // url: '',
      couponList:{},
      couponAmount:0,
      spData:[],
      textarea:'',
      order:{},
      multipleSelection:[],
      productList:{},
      dialogFormVisible:false,
      orderItem:{},
      region:'',
      city:'',
      province:'',
      buyer:{},
    }
  },
  watch:{
    selectA(){
      this.price=[]
      this.stock=[]
      for(let i of this.goods.stockList){
        if(this.selectA[0] === i.spData[0].inputList && this.selectA[1] === i.spData[1].inputList){
          this.price.push(i.price);
          this.stock.push(i.stock);
        }
      }
    }
  },
  created() {
    this.id = this.$route.query.id;
    this.load()
    // this.getData()
  },
  methods: {
    load() {
      this.request.get("/product/showProduct?id=" + this.id).then(res => {
        this.goods = res.data
        this.findAbleCoupon()
      })
    },
    findAbleCoupon(){
      this.request.get("/couponhistories/getAbleCoupon/"+this.memberId).then(res=>{
        this.couponList = res.data
      })
    },
    handleSelectionChange1(val) {
      this.couponAmount = 0
      this.multipleSelection = val;
      //进行计算
      if(val && val.length){
        val.forEach(item=>{
          this.couponAmount = item.amount
        })
      }
      if (val.length > 1) {
        this.$refs.singleTable.clearSelection()
        this.$refs.singleTable.toggleRowSelection(val.pop())
      }
    },
    checkSelectable(row) {
      return row.minPoint <= this.form.num*this.goods.price
    },
    addCart(goods) {
      if (!this.user.username) {
        this.$message.warning("请登录后操作")
        return
      }
      if(this.selectA.length === 0){
        this.$message.warning("请选择款式")
        return
      }
      let spData = '[{"key":"颜色","value":"'+this.selectA[0]+'"},{"key":"尺寸","value":"'+this.selectA[1]+'"}]'
      this.cartItem.productId= goods.id
      this.cartItem.memberId = this.memberId
      this.cartItem.quantity = this.form.num
      this.cartItem.productPic = goods.pic
      this.cartItem.productName = goods.name
      this.cartItem.price = goods.price
      this.cartItem.deleteStatus = 1
      this.cartItem.memberNickname = this.user.nickname
      this.cartItem.spData = spData
      this.request.post("/cart",this.cartItem).then(res=>{
        if(res){
          this.$message.success("添加成功！")
        }else{
          this.$message.error("网络开小差啦！请稍后再试")
        }
      })
      this.$router.push('/front/shoppingCart')
      console.log(this.cartItem)
    },

    getInputListArr(inputList) {
      return inputList.split(',');
    },

    back() {
      this.$router.go(-1);
    },
    handleBuy(){
      if(this.selectA.length === 0){
        this.$message.warning("请选择款式")
        return
      }
      this.textarea = ''
      this.receiverAddress=''
      this.receiverPhone=''
      this.receiverName=''
      this.city = ''
      this.region = ''
      this.province = ''
      this.productList = [this.goods]
      console.log(this.goods)
      this.dialogFormVisible = true
    },
    handleSubmit(){

      if(this.$refs.singleTable.selection[0]==null)
      {this.order.couponId = null}
      else{this.order.couponId = this.$refs.singleTable.selection[0].couponId}
      this.order.couponAmount = this.couponAmount
      this.order.totalAmount = this.goods.price * this.form.num
      this.order.payType = 0
      this.order.sourceType = 0
      this.order.status = 0
      this.order.receiverProvince  = this.province
      this.order.receiverCity = this.city
      this.order.receiverRegion = this.region
      this.order.orderType = 0
      this.order.note = this.textarea
      this.order.memberUsername = this.user.nickname
      this.order.memberId = this.memberId
      this.order.payAmount = this.order.totalAmount - this.couponAmount
      this.order.receiverName = this.receiverName
      this.order.receiverPhone = this.receiverPhone
      this.order.receiverDetailAddress = this.receiverAddress

      this.request.post("/order/buy",JSON.stringify(this.order)).then(res=>{
        if(res){
          this.$message.success("下单成功，请及时支付")
          this.orderId = res.data
          this.dialogFormVisible = false
          this.addOrderItem()
          this.load()
        }else{
          this.$message.error("服务器开小差啦")
          this.dialogFormVisible = false
        }
      })
    },
    addOrderItem(){
      let spData = '[{"key":"颜色","value":"'+this.selectA[0]+'"},{"key":"尺寸","value":"'+this.selectA[1]+'"}]'
      this.orderItem.orderId= this.orderId
      this.orderItem.productId = this.goods.id
      this.orderItem.productPic = this.goods.pic
      this.orderItem.productName = this.goods.name
      this.orderItem.productSn = this.goods.productSn
      this.orderItem.productPrice = this.goods.price
      this.orderItem.productQuantity = this.form.num
      this.orderItem.realAmount = this.order.totalAmount - this.couponAmount
      this.orderItem.spData = spData
      this.orderItem.productSubTitle = this.goods.subtitle
      this.request.post("/order/addOrderItem",JSON.stringify(this.orderItem)).then(res=>{
      })
    },
    onSelectRegion(data) {
      this.province = data.province.value;
      this.city = data.city.value;
      this.region = data.area.value;
    },
    fill(){
      this.request.get("/user/" + localStorage.getItem("id")).then(res => {
        console.log(res.province)
        this.province = res.province
        this.city = res.city
        this.region = res.region
        this.receiverAddress = res.detailAddress
        this.receiverName = res.nickname
        this.receiverPhone = res.phone
      })
    }
  }
}
</script>

<style scoped>
.item1 {
  padding: 10px;
  color: #666;
}

.r{
  position:absolute;
  right:5px;
  bottom:5px;
}
</style>